package serivce

import (
	"golang.org/x/crypto/bcrypt"
	"guard/internal/app/user/models"
	"guard/internal/errors"
	"guard/internal/tool"
)

/*
用户操作
*/

func (s *userServiceImpl) RegisterUser(user *models.User) error {

	_, name, _, _, _, _, _, err := s.st.SelUser(user.Username)
	if err != nil || len(name) > 0 {
		return errors.OtherError("用户已存在")
	}

	bcrPassword, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)
	if err != nil {
		return errors.OtherError("密码不符合规范")
	}
	// 设置必须数据
	user.Password = string(bcrPassword)
	user.Enable = true
	user.UserScopeTag = "userinfo"

	// 头像存储到本地
	img := tool.NewImg(user.Picture, user.Username)
	imgFile, err := img.StoreImgLocal()
	if err != nil {
		return errors.OtherError("注册失败，头像上传失败")
	}
	user.Picture = imgFile

	err = s.st.SaveOrUpdateUser(*user)
	if err != nil {
		return errors.OtherError("注册失败，请联系管理员")
	}

	return nil
}

func (s *userServiceImpl) ModifyUserInfo(username, nickName, picTure string) error {
	// 1.查询一次用户信息
	id, uName, uPwd, _, picFile, userTag, enable, err := s.st.SelUser(username)
	if err != nil {
		return errors.OtherError("错误的用户信息")
	}
	nmu := models.User{
		Id:           id,
		Username:     uName,
		Password:     uPwd,
		Nickname:     nickName,
		Picture:      picFile,
		Enable:       enable,
		UserScopeTag: userTag,
	}

	// 1.2.头像存储到本地
	if picTure != "" {
		img := tool.NewImg(picTure, username)
		fileName, err := img.StoreImgLocal()
		if err != nil {
			return errors.OtherError("修改失败，头像上传失败")
		}
		nmu.Picture = fileName
	}

	// 2.保存新的用户信息，留下id
	err = s.st.SaveOrUpdateUser(nmu)
	if err != nil {
		return errors.OtherError("修改失败")
	}
	return nil
}

func (s *userServiceImpl) ModifyUserPassword(username, oldPwd, newPwd string) error {
	// 1.查询用户
	id, uName, password, nickName, picFile, userTag, enable, err := s.st.SelUser(username)
	if err != nil {
		return errors.OtherError("错误的用户信息")
	}
	// 1.判断用户旧密码是否正确
	err = bcrypt.CompareHashAndPassword([]byte(password), []byte(oldPwd))
	if err != nil {
		return errors.OtherError("旧密码不相同")
	}
	// 2.加密新密码
	newPwdBcrtpy, err := bcrypt.GenerateFromPassword([]byte(newPwd), bcrypt.DefaultCost)
	// 3.保存信息
	user := models.User{
		Id:           id,
		Username:     uName,
		Password:     string(newPwdBcrtpy),
		Nickname:     nickName,
		Picture:      picFile,
		Enable:       enable,
		UserScopeTag: userTag,
	}
	err = s.st.SaveOrUpdateUser(user)
	if err != nil {
		return errors.OtherError("修改密码失败")
	}
	return nil
}
